// 默认检查间隔（分钟）
let checkInterval = 5;

// 初始化时获取配置的间隔时间
chrome.storage.sync.get({ interval: 5 }, (result) => {
  checkInterval = result.interval;
  console.log('初始化检查间隔:', checkInterval);
});

// 监听配置更改
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'updateInterval') {
    checkInterval = message.interval;
    console.log('更新检查间隔:', checkInterval);
    setupAlarm();
  } else if (message.type === 'manualCheck') {
    // 立即执行检查
    checkNotifications()
      .then(() => {
        if (message.waitForResponse) {
          sendResponse({ success: true });
        }
      })
      .catch(error => {
        console.error('检查失败:', error);
        if (message.waitForResponse) {
          sendResponse({ success: false, error: error.message });
        }
      });
    
    // 返回 true 表示将异步发送响应
    return true;
  }
});

// 插件安装或更新时执行检查
chrome.runtime.onInstalled.addListener(() => {
  console.log('插件已安装/更新，执行首次检查');
  checkNotifications();
});

// 浏览器启动时执行检查
chrome.runtime.onStartup.addListener(() => {
  console.log('浏览器启动，执行检查');
  checkNotifications();
});

// 设置定时器
function setupAlarm() {
  chrome.alarms.clear('checkGiteeNotifications', () => {
    chrome.alarms.create('checkGiteeNotifications', {
      periodInMinutes: checkInterval
    });
    console.log('已设置定时器，间隔:', checkInterval);
  });
}

// 监听定时器
chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === 'checkGiteeNotifications') {
    console.log('定时器触发检查');
    checkNotifications();
  }
});

// 检查通知的函数
async function checkNotifications() {
  console.log('开始检查通知...');
  try {
    // 获取上次通知的时间
    const { lastNotificationTime } = await chrome.storage.local.get('lastNotificationTime');
    const now = Date.now();
    
    // 如果距离上次通知不足30秒，则跳过
    if (lastNotificationTime && (now - lastNotificationTime < 30000)) {
      console.log('跳过重复通知');
      return;
    }
    
    // 更新后通知时间
    await chrome.storage.local.set({ lastNotificationTime: now });
    
    // 1. 获取 access token
    const { accessToken } = await chrome.storage.sync.get('accessToken');
    
    if (!accessToken) {
      console.log('未配置 Access Token');
      chrome.notifications.create({
        type: 'basic',
        iconUrl: chrome.runtime.getURL('icons/icon128.png'),
        title: 'Gitee 通知助手',
        message: '请先配置 Access Token',
        priority: 2
      });
      return;
    }

    // 只清理历史记录，保留其他配置
    const { lastSuccessfulFetch } = await chrome.storage.sync.get('lastSuccessfulFetch');
    await chrome.storage.local.clear();
    console.log('已清理本地缓存');

    // 2. 获取当前用户资料
    const userResponse = await fetch('https://gitee.com/api/v5/user', {
      headers: {
        'Accept': 'application/json',
        'Authorization': `token ${accessToken}`
      }
    });

    if (!userResponse.ok) {
      throw new Error('获取用户信息失败');
    }

    const userInfo = await userResponse.json();
    console.log('当前用户:', userInfo);

    if (!userInfo.login) {
      throw new Error('获取用户名失败');
    }

    // 3. 获取企业列表
    const enterpriseResponse = await fetch('https://gitee.com/api/v5/user/enterprises', {
      headers: {
        'Accept': 'application/json',
        'Authorization': `token ${accessToken}`
      }
    });

    if (!enterpriseResponse.ok) {
      throw new Error('获取企业列表失败');
    }

    const enterprises = await enterpriseResponse.json();
    if (!enterprises || enterprises.length === 0) {
      throw new Error('没有可用的企业空间');
    }

    console.log('获取到的企业列表:', enterprises);
    
    // 确保企业数据格式正确
    if (!enterprises[0].path) {
      throw new Error('企业数据格式不正确：缺少 path');
    }

    // 获取已选择的企业，如果没有则使用第一个
    const { selectedEnterprise } = await chrome.storage.sync.get('selectedEnterprise');
    const currentEnterprise = selectedEnterprise || enterprises[0].path;
    console.log('已选择的企业:', currentEnterprise);
    // 4. 获取当前企业下的 issues
    // 使用 encodeURIComponent 确保企业名称正确编码
    const encodedEnterprise = encodeURIComponent(currentEnterprise);
    console.log('编码后的企业名称:', encodedEnterprise);

    const params = new URLSearchParams({
      // 只获取打开的 issues
      state: 'open',
      // 按创建时间排序
      sort: 'created',
      // 降序排列（最新的在前）
      direction: 'desc',
      // 只获取分配给我的
      assignee: userInfo.login,
      // 添加时间戳避免缓存
      _: Date.now(),
      page: 1,
      per_page: 50
    }).toString();

    const response = await fetch(`https://gitee.com/api/v5/enterprises/${encodedEnterprise}/issues?${params}`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json;charset=UTF-8',
        'Authorization': `token ${accessToken}`,
        'Cache-Control': 'no-cache'
      }
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('API 错误响应:', {
        status: response.status,
        statusText: response.statusText,
        error: errorText
      });
      throw new Error(`获取 Issues 失败: ${response.status}`);
    }

    const issues = await response.json();
    console.log('获取到的 Issues:', issues);

    if (issues && issues.length > 0) {
      const simplifiedBugs = issues.map(issue => ({
        id: issue.id,
        title: issue.title || '',
        html_url: `https://e.gitee.com/${currentEnterprise}/issues/list?issue=${issue.number}`,
        created_at: issue.created_at || new Date().toISOString(),
        number: issue.number,
        issue_state: issue.issue_state || 'open',
        issue_type: issue.issue_type,
        type: 'issue'
      }));

      console.log('处理后的 issues:', simplifiedBugs);

      // 保存数据
      const updateTime = new Date().toLocaleString();
      await chrome.storage.sync.set({ 
        bugHistory: simplifiedBugs,
        selectedEnterprise: currentEnterprise,
        lastUpdateTime: updateTime
      });

      console.log('成功保存 issue 列表:', simplifiedBugs);

      // 发送通知
      const latestBug = simplifiedBugs[0];
      console.log('最新 Bug:', latestBug);
      const notificationMessage = `状态: ${latestBug.issue_state}\n${latestBug.title}\n\n${latestBug.issue_type || '任务'}: #${latestBug.number}\n`;
      const notificationId = `gitee-notification-${Date.now()}`;
      chrome.notifications.create(
        notificationId,
        {
          type: 'basic',
          iconUrl: chrome.runtime.getURL('icons/icon128.png'),
          title: 'Gitee issue 通知',
          message: notificationMessage,
          priority: 2,
          buttons: [
            { title: '查看详情' }
          ]
        }, () => {
          chrome.storage.local.set({ [notificationId]: latestBug.html_url });
        });
    } else {
      console.log('没有新通知');
      await chrome.storage.sync.set({ bugHistory: [] });
    }
  } catch (error) {
    console.error('检查通知时出错:', error);
    throw error;
  }
}

// 添加通知按钮点击事件
chrome.notifications.onButtonClicked.addListener((notificationId, buttonIndex) => {
  if (buttonIndex === 0) {
    // 获取保存的 URL 并打开
    chrome.storage.local.get(notificationId, (result) => {
      const url = result[notificationId];
      if (url) {
        chrome.tabs.create({ url });
        // 清理存储的 URL
        chrome.storage.local.remove(notificationId);
      } else {
        // 如果没有找到 URL，打开默认页面
        chrome.tabs.create({ 
          url: 'https://gitee.com/dashboard/issues?assignee=me&state=opened' 
        });
      }
    });
  }
});
